from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from rest_framework.filters import BaseFilterBackend


class BaseUserFilter(object):
    def token_queryset(self, request, queryset):
        if not request.user.is_superuser:
            queryset = queryset.filter(author=request.user)
        return queryset


class PostsFilter(BaseFilterBackend):
    """
    Posts 过滤
    """

    def filter_queryset(self, request, queryset, view):
        kw = request.query_params.get('kw')
        type_id = int(request.query_params.get('type', 0))
        topic_id = request.query_params.get('topic', '0')
        if kw:
            queryset = queryset.filter(
                Q(title__contains=kw) |
                Q(content__contains=kw)
            )
        if type_id:
            queryset = queryset.filter(type_id=type_id)
        if topic_id != '0':
            queryset = queryset.filter(topic_id=topic_id)
        return queryset.distinct()


class UserPostsFilter(BaseUserFilter, PostsFilter):
    """
    Posts 过滤
    """

    def filter_queryset(self, request, queryset, view):
        queryset = super(UserPostsFilter, self).filter_queryset(request, queryset, view)
        return self.token_queryset(request, queryset)


class TopicsFilter(BaseFilterBackend):
    """
    Topics 过滤
    """

    def filter_queryset(self, request, queryset, view):
        kw = request.query_params.get('kw')
        topic_id = request.query_params.get('topic', '')
        if kw:
            queryset = queryset.filter(
                Q(title__contains=kw) |
                Q(desc__contains=kw)
            )
        if topic_id:
            queryset = queryset.filter(pk=topic_id)
        return queryset.distinct()


class UserTopicsFilter(BaseUserFilter, TopicsFilter):
    """
    Topics 过滤
    """

    def filter_queryset(self, request, queryset, view):
        queryset = super(UserTopicsFilter, self).filter_queryset(request, queryset, view)
        return self.token_queryset(request, queryset)
